package com.hxzy.tms.aciton;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;

import com.hxzy.tms.aciton.vo.UserVo;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.service.ServiceResult;
import com.hxzy.tms.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;

public class RegisterAction extends AbstractAction implements Preparable {
    private static final long serialVersionUID = -4745247408141363096L;

    private static final String KEY = "user_in_register";

    private UserVo user;
    private String vercode;
    private UserService userService;

    public void prepare() throws Exception {
        UserVo userInSession = (UserVo) ActionContext.getContext().getSession().get(KEY);
        if (userInSession != null) {
            user = userInSession;
        }
    }

    public String step1() {
        SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext.getContext().getSession();
        session.put(KEY, user);

        if (isGET()) {
            return INPUT;
        }
        return "step2";
    }

    public String step2() {
        SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext.getContext().getSession();
        session.put(KEY, user);

        if (isGET()) {
            return INPUT;
        }

        return "step3";
    }

    public String step3() {
        if (isGET()) {
            return INPUT;
        }

        Map<String, Object> data = new HashMap<String, Object>();
        ServiceResult<User> result = userService.register(user.getEmail(), user.getPasswd(), user.getNickname(),
                user.getRealname(), user.getPhone(), vercode, ipv4());
        data.put("status", result.status);
        data.put("message", result.message);
        writeJson(data);
        if(result.status == 1) {
            ActionContext.getContext().getSession().remove(KEY);
        }
        return null;
    }

    public UserVo getUser() {
        return user;
    }

    public void setUser(UserVo user) {
        this.user = user;
    }

    public String getVercode() {
        return vercode;
    }

    public void setVercode(String vercode) {
        this.vercode = vercode;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
